﻿using AutoMapper;
using Decoration.Api.Comm;
using Decoration.Comm;
using Decoration.IService;
using Decoration.Models;
using Decoration.Models.Dto;
using Decoration.Models.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Decoration.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
  
    public class UserProcedureController : ControllerBase
    {
        private readonly IUserProcedureService svc;
        private readonly IProjectInfoService projectSvc;
        private readonly IMapper mapper;

        public UserProcedureController(IUserProcedureService svc, IProjectInfoService projectSvc, IMapper mapper)
        {
            this.svc = svc;
            this.projectSvc = projectSvc;
            this.mapper = mapper;
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <returns></returns>
        [HttpGet("getAll")]
        public Result Get()
        {
            var data = svc.Query(o => o.Status == 1);

            return new Result() { code = 1, msg = "成功", data = data };
        }

        /// <summary>
        /// 根据项目获取工序
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("getByProject")]
        public Result<IEnumerable<UserProcedureDto>> GetByProject(int projectId)
        {
            string sql = @"select up.*
	        ,checkstu.DictName as 'CheckStatusText'
	        ,stu.DictName as 'StatusText'
	        ,l.ProfilePhoto
	        from UserProcedures up
	        inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态'
	        inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
	        inner join Base_LoginInfos l on l.UserId = up.Employee
	        where ProjectId = @projectId";

            var data = DapperHelper.Query<UserProcedureDto>(sql,new {projectId});

            return new Result<IEnumerable<UserProcedureDto>>() { code=1,msg="成功",data = data};
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="projectName"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public PagedResult<UserProcedureDto> Get(string? projectName = "", int pageSize = 10, int pageIndex = 1)
        {

            string sql = @"select up.*
		                ,pj.ProjectName
		                ,checkstu.DictName as 'CheckStatusText'
		                ,stu.DictName as 'StatusText'
	                from UserProcedures up
	                inner join ProjectInfos pj on up.ProjectId = pj.Id
	                inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态'
	                inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
	                    where 1=1";
            if (!string.IsNullOrEmpty(sql)) sql += " and projectName like @projectName";

            string totalSql = $"select count(*) from ({sql}) as ff";


            int total = svc.ExecuteScalar<int>(sql, new { projectName = $"%{projectName}%" });

            sql += " order by createTime desc";
            sql += " offset @pageSize*(@pageIndex-1) rows fetch next @pageSize rows only";

            var data = svc.Query<UserProcedureDto>(sql, new { projectName = $"%{projectName}%", pageSize, pageIndex });

            return new PagedResult<UserProcedureDto>() { code = 1, msg = "成功", total = total, data = data };
        }

        /// <summary>
        /// 我的任务
        /// </summary>
        /// <returns></returns>
        [HttpGet("getMy")]
        [MyAuthorize]
        public PagedResult<UserProcedureDto> GetMy(string? ProcedureName = "", int pageSize = 10, int pageIndex = 1)
        {
            var auth = RouteData.Values["auth"] as AuthInfo;

            string sql = @"select up.*
		                ,pj.ProjectName
		                ,checkstu.DictName as 'CheckStatusText'
		                ,stu.DictName as 'StatusText'
	                    from UserProcedures up
	                    inner join ProjectInfos pj on up.ProjectId = pj.Id
	                    inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态'
	                    inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
	                    where Employee = @userId";

            if (!string.IsNullOrEmpty(sql)) sql += " and ProcedureName like @ProcedureName";
            string totalSql = $"select count(*) from ({sql}) ff";


            int total = svc.ExecuteScalar<int>(totalSql, new { ProcedureName = "%"+ProcedureName+"%", auth.UserId });

            sql += " order by createTime desc";
            sql += " offset @pageSize*(@pageIndex-1) rows fetch next @pageSize rows only";

            var data = svc.Query<UserProcedureDto>(sql, new { ProcedureName = "%" + ProcedureName + "%",  auth.UserId, pageSize, pageIndex });

            return new PagedResult<UserProcedureDto>() { code = 1, msg = "成功", total = total, data = data };
       
        }
        /// <summary>
        /// 我的任务
        /// </summary>
        /// <returns></returns>
        [HttpGet("AppMy")]
        public PagedResult<UserProcedureDto> AppMy(int Customer , int Id )
        {
            string sql = @"select up.*
		                ,pj.ProjectName
		                ,checkstu.DictName as 'CheckStatusText'
		                ,stu.DictName as 'StatusText'
	                    from UserProcedures up
	                    inner join ProjectInfos pj on up.ProjectId = pj.Id
	                    inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态'
	                    inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
	                     where pj.Customer =@Customer and pj.Id=@Id";
            string totalSql = $"select count(*) from ({sql}) ff";

            int total = svc.ExecuteScalar<int>(totalSql, new { Customer, Id });
            var data = svc.Query<UserProcedureDto>(sql,new {Customer,Id});

            return new PagedResult<UserProcedureDto>() { code = 1, msg = "成功",data = data,total=total };

        }
        /// <summary>
        /// 我的任务
        /// </summary>
        /// <returns></returns>
        [HttpGet("Mytesk")]
        [MyAuthorize]
        public PagedResult<UserProcedureDto> Mytesk()
        {

            var auth = RouteData.Values["auth"] as AuthInfo;
            string sql = @"select up.*
		                ,pj.ProjectName
		                ,checkstu.DictName as 'CheckStatusText'
		                ,stu.DictName as 'StatusText'
	                    from UserProcedures up
	                    inner join ProjectInfos pj on up.ProjectId = pj.Id
	                    inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态'
	                    inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
	                    where Employee = @userId and up.Status != 2";
            string totalSql = $"select count(*) from ({sql})";
            var data = svc.Query<UserProcedureDto>(sql, new { auth.UserId });

            return new PagedResult<UserProcedureDto>() { code = 1, msg = "成功", data = data };

        }
        /// <summary>
        /// 历史任务
        /// </summary>
        /// <returns></returns>
        [HttpGet("HistoryAppMy")]
        [MyAuthorize]
        public PagedResult<UserProcedureDto> HistoryAppMy()
        {

            var auth = RouteData.Values["auth"] as AuthInfo;
            string sql = @"select up.*
		                ,pj.ProjectName
		                ,checkstu.DictName as 'CheckStatusText'
		                ,stu.DictName as 'StatusText'
	                    from UserProcedures up
	                    inner join ProjectInfos pj on up.ProjectId = pj.Id
	                    inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态'
	                    inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
	                    where Employee = @userId and up.Status = 2";
            string totalSql = $"select count(*) from ({sql})";
            var data = svc.Query<UserProcedureDto>(sql, new { auth.UserId });

            return new PagedResult<UserProcedureDto>() { code = 1, msg = "成功", data = data };

        }
        //已经完成的任务
        [HttpGet("Finish")]
        [MyAuthorize]
        public PagedResult<UserProcedureDto> Finish(string? ProcedureName = "", int pageSize = 10, int pageIndex = 1) {
            var auth = RouteData.Values["auth"] as AuthInfo;
            string sql = @"select up.*
		                ,pj.ProjectName
		                ,checkstu.DictName as 'CheckStatusText'
		                ,stu.DictName as 'StatusText'
	                    from UserProcedures up
	                    inner join ProjectInfos pj on up.ProjectId = pj.Id
	                    inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态' and up.Status=2
	                    inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
						where Employee = @userId";

            if (!string.IsNullOrEmpty(sql)) sql += " and ProcedureName like @ProcedureName";
            string totalSql = $"select count(*) from ({sql})";


            int total = svc.ExecuteScalar<int>(sql, new { ProcedureName = "%" + ProcedureName + "%", auth.UserId });

            sql += " order by createTime desc";
            sql += " offset @pageSize*(@pageIndex-1) rows fetch next @pageSize rows only";

            var data = svc.Query<UserProcedureDto>(sql, new { ProcedureName = "%" + ProcedureName + "%", auth.UserId, pageSize, pageIndex });

            return new PagedResult<UserProcedureDto>() { code = 1, msg = "成功", total = total, data = data };

        }

        //未完成的任务
        [HttpGet("IncompletTtasks")]
        [MyAuthorize]
        public PagedResult<UserProcedureDto> IncompletTtasks(string? ProcedureName = "", int pageSize = 10, int pageIndex = 1)
        {
            var auth = RouteData.Values["auth"] as AuthInfo;
            string sql = @"select up.*
		                ,pj.ProjectName
		                ,checkstu.DictName as 'CheckStatusText'
		                ,stu.DictName as 'StatusText'
	                    from UserProcedures up
	                    inner join ProjectInfos pj on up.ProjectId = pj.Id
	                    inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态'
	                    inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
						where Employee = @userId  and up.Status in (1,5,4)";

            if (!string.IsNullOrEmpty(sql)) sql += " and ProcedureName like @ProcedureName";
            string totalSql = $"select count(*) from ({sql})";


            int total = svc.ExecuteScalar<int>(sql, new { ProcedureName = "%" + ProcedureName + "%", auth.UserId });

            sql += " order by createTime asc";
            sql += " offset @pageSize*(@pageIndex-1) rows fetch next @pageSize rows only";

            var data = svc.Query<UserProcedureDto>(sql, new { ProcedureName = "%" + ProcedureName + "%", auth.UserId, pageSize, pageIndex });

            return new PagedResult<UserProcedureDto>() { code = 1, msg = "成功", total = total, data = data };

        }
        
        /// <summary>
        /// 验收通过
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("accept")]
        public Result Accept(int id)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            data.CheckStatus = 2;

            var procedureArr = svc.Query(o=>o.ProjectId == data.ProjectId);

            // 修改下一个工序状态
            var nextProcedure = procedureArr.Where(o=>o.ProcedureOrder-data.ProcedureOrder == 1).FirstOrDefault();
            if(nextProcedure != null)
            {
                nextProcedure.Status = 1;
                svc.Update(nextProcedure);
            }

            // 判断工序是否全部完成
            if (procedureArr.Where(o => o.CheckStatus != 2).Count() == 1)
            {
                // 完成 修改项目状态
                var project = projectSvc.Get(p=>p.Id == data.ProjectId);
                project.CompletedStatus = 2;
                projectSvc.Update(project);
            }

            if (svc.Update(data))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = -1, msg = "失败" };
        }

        /// <summary>
        /// 驳回
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        [HttpPut("reject")]
        public Result Reject(int id)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            data.CheckStatus = 3;
            data.Status = 1;

            if (svc.Update(data))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = -1, msg = "失败" };
        }

        /// <summary>
        /// 获取单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public Result Get(int id)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            return new Result() { code = 1, msg = "成功", data = data };
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public Result Post(UserProcedureRegisterDto dto)
        {
            var entity = mapper.Map<IEnumerable<UserProcedure>>(dto.Procedures);

            if (entity.Count() == 0) return new Result() { code = 1, msg = "数据为空" };


            if (svc.AddRange(entity))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = 1, msg = "失败" };
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public Result Put(int id, UserProcedurePostDto dto)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            var entity = mapper.Map(dto, data);

            if (svc.Update(entity))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = -1, msg = "失败" };
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public Result Delete(int id)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            data.Status = 0;

            if (svc.Update(data))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = -1, msg = "失败" };
        }
    }
}
